using AutoMapper;
using BackData;
using Domain.Warehousies;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.Warehouse.laneway;

namespace Team.API.Applocation.Hanldler.Warehouse.laneway
{
    /// <summary>
    /// 更新巷道命令处理器
    /// </summary>
    public class UpdateLanewayHandler : IRequestHandler<UpdateLanewayCommand, APIResult<int>>
    {
        private readonly IMapper _mapper;
        private readonly IRepository<Lanewaymodel> _lanewayRep;
        private readonly ILogger<UpdateLanewayHandler> _logger;

        public UpdateLanewayHandler(
            IMapper mapper,
            IRepository<Lanewaymodel> lanewayRep,
            ILogger<UpdateLanewayHandler> logger)
        {
            _mapper = mapper;
            _lanewayRep = lanewayRep;
            _logger = logger;
        }

        public async Task<APIResult<int>> Handle(UpdateLanewayCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查找巷道
                var laneway = await _lanewayRep.GetAll()
                    .Where(x => x.Id == request.Id && !x.IsDel)
                    .FirstAsync();

                if (laneway == null)
                {
                    return new APIResult<int>
                    {
                        Code = StateCode.Fail,
                        Message = "巷道不存在",
                        Result = 0
                    };
                }

                // 如果更新巷道编号，检查是否重复
                if (!string.IsNullOrEmpty(request.Lanewaycode) && request.Lanewaycode != laneway.Lanewaycode)
                {
                    var existingLaneway = await _lanewayRep.GetAll()
                        .Where(x => x.Lanewaycode == request.Lanewaycode && x.Id != request.Id && !x.IsDel)
                        .FirstAsync();

                    if (existingLaneway != null)
                    {
                        return new APIResult<int>
                        {
                            Code = StateCode.Fail,
                            Message = $"巷道编号 {request.Lanewaycode} 已存在",
                            Result = 0
                        };
                    }
                }

                // 更新字段（只更新非空字段）
                if (!string.IsNullOrEmpty(request.Lanewaycode))
                    laneway.Lanewaycode = request.Lanewaycode;

                if (!string.IsNullOrEmpty(request.Lanewayname))
                    laneway.Lanewayname = request.Lanewayname;

                if (request.Lanewaystate.HasValue)
                    laneway.Lanewaystate = (Tunnelcondition)request.Lanewaystate.Value;

                if (request.Remark != null)
                    laneway.Remark = request.Remark;

                var result = await _lanewayRep.UpdateAsync(laneway);

                if (result > 0)
                {
                    _logger.LogInformation($"巷道更新成功: ID={request.Id}");
                    return new APIResult<int>
                    {
                        Code = StateCode.OK,
                        Message = "巷道更新成功",
                        Result = result
                    };
                }
                else
                {
                    return new APIResult<int>
                    {
                        Code = StateCode.Fail,
                        Message = "巷道更新失败",
                        Result = 0
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "巷道更新失败");
                return new APIResult<int>
                {
                    Code = StateCode.Fail,
                    Message = $"巷道更新失败: {ex.Message}",
                    Result = 0
                };
            }
        }
    }
}
